import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import '../models/important_day.dart';
import '../providers/important_days_provider.dart';
import '../screens/add_important_day_screen.dart';

class ImportantDayCard extends StatefulWidget {
  final ImportantDay importantDay;
  final VoidCallback? onTap;
  final bool isGrayedOut;

  const ImportantDayCard({
    super.key,
    required this.importantDay,
    this.onTap,
    this.isGrayedOut = false,
  });

  @override
  State<ImportantDayCard> createState() => _ImportantDayCardState();
}

class _ImportantDayCardState extends State<ImportantDayCard>
    with SingleTickerProviderStateMixin {
  late AnimationController _controller;
  late Animation<double> _animation;
  bool _isFlipped = false;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      duration: const Duration(milliseconds: 600),
      vsync: this,
    );
    _animation = Tween<double>(
      begin: 0.0,
      end: 1.0,
    ).animate(CurvedAnimation(
      parent: _controller,
      curve: Curves.easeInOut,
    ));
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  void _flip() {
    // 添加触觉反馈
    HapticFeedback.lightImpact();
    
    if (_isFlipped) {
      _controller.reverse();
    } else {
      _controller.forward();
    }
    setState(() {
      _isFlipped = !_isFlipped;
    });
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: _flip,
      onLongPress: () => _showEditMenu(context),
      child: AnimatedBuilder(
        animation: _animation,
        builder: (context, child) {
          final isShowingFront = _animation.value < 0.5;
          return Transform(
            alignment: Alignment.center,
            transform: Matrix4.identity()
              ..setEntry(3, 2, 0.001)
              ..rotateY(_animation.value * 3.14159),
            child: isShowingFront ? _buildFrontCard() : _buildBackCard(),
          );
        },
      ),
    );
  }

  Widget _buildFrontCard() {
    final daysUntil = widget.importantDay.daysUntil;
    final isToday = widget.importantDay.isToday;
    final isPast = widget.importantDay.isPast;

    return Card(
      elevation: widget.isGrayedOut ? 1 : 2,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(12),
        side: BorderSide(
          color: widget.isGrayedOut ? Colors.grey.shade200 : Colors.grey.shade100,
          width: 1,
        ),
      ),
      color: widget.isGrayedOut ? Colors.grey.shade100 : Colors.white,
      margin: EdgeInsets.zero,
      child: Padding(
        padding: const EdgeInsets.all(8),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisSize: MainAxisSize.min,
          children: [
            // 顶部：标题
            Text(
              widget.importantDay.title,
              style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.bold,
                color: widget.isGrayedOut ? Colors.grey.shade600 : Colors.pink.shade700,
              ),
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
            ),
            
            const SizedBox(height: 4),
            
            // 分类
            Text(
              widget.importantDay.category,
              style: TextStyle(
                fontSize: 9,
                color: widget.isGrayedOut ? Colors.grey.shade500 : Colors.grey.shade600,
              ),
            ),
            
            const SizedBox(height: 6),
            
            // 主要内容 - 天数显示（左对齐，在分类下面）
            _buildCountdownWidget(daysUntil, isToday, isPast),
            
            const Spacer(),
            
            // 底部：左下角日期，右下角表情
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              crossAxisAlignment: CrossAxisAlignment.end,
              children: [
                // 左下角日期
                Text(
                  _formatDate(widget.importantDay.date),
                  style: TextStyle(
                    fontSize: 9,
                    color: widget.isGrayedOut ? Colors.grey.shade400 : Colors.grey.shade500,
                  ),
                ),
                // 右下角表情
                Text(
                  widget.importantDay.emoji,
                  style: const TextStyle(fontSize: 24),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildBackCard() {
    return Transform(
      alignment: Alignment.center,
      transform: Matrix4.identity()..rotateY(3.14159),
      child: Card(
        elevation: widget.isGrayedOut ? 1 : 2,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(12),
          side: BorderSide(
            color: widget.isGrayedOut ? Colors.grey.shade200 : Colors.grey.shade100,
            width: 1,
          ),
        ),
        margin: EdgeInsets.zero,
        color: Colors.transparent,
        child: Container(
          decoration: BoxDecoration(
            gradient: LinearGradient(
              begin: Alignment.topLeft,
              end: Alignment.bottomRight,
              colors: widget.isGrayedOut 
                  ? [Colors.grey.shade100, Colors.grey.shade200]
                  : [Colors.pink.shade50, Colors.pink.shade100],
            ),
            borderRadius: BorderRadius.circular(12),
          ),
          child: Padding(
            padding: const EdgeInsets.all(8),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisSize: MainAxisSize.min,
              children: [
                // 顶部：标题
                Text(
                  widget.importantDay.title,
                  style: TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.bold,
                    color: widget.isGrayedOut ? Colors.grey.shade600 : Colors.pink.shade700,
                  ),
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                ),
                
                const SizedBox(height: 6),
                
                // 描述
                Expanded(
                  child: Text(
                    widget.importantDay.description,
                    style: TextStyle(
                      fontSize: 10,
                      color: widget.isGrayedOut ? Colors.grey.shade500 : Colors.pink.shade600,
                      height: 1.3,
                    ),
                    maxLines: 3,
                    overflow: TextOverflow.ellipsis,
                  ),
                ),
                
                // 备注
                if (widget.importantDay.note != null) ...[
                  const SizedBox(height: 4),
                  Text(
                    widget.importantDay.note!,
                    style: TextStyle(
                      fontSize: 8,
                      color: widget.isGrayedOut ? Colors.grey.shade400 : Colors.pink.shade500,
                      fontStyle: FontStyle.italic,
                    ),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                ],
                
                const SizedBox(height: 6),
                
                // 底部：左下角日期，右下角表情
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  crossAxisAlignment: CrossAxisAlignment.end,
                  children: [
                    // 左下角日期
                    Text(
                      _formatDate(widget.importantDay.date),
                      style: TextStyle(
                        fontSize: 9,
                        color: widget.isGrayedOut ? Colors.grey.shade400 : Colors.pink.shade400,
                      ),
                    ),
                    // 右下角表情
                    Text(
                      widget.importantDay.emoji,
                      style: const TextStyle(fontSize: 24),
                    ),
                  ],
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  String _formatDate(DateTime date) {
    return '${date.year}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')}';
  }

  String _getCountdownText(int daysUntil, bool isToday, bool isPast) {
    if (isToday) {
      return '今天就是';
    } else if (isPast) {
      return '已过去${-daysUntil}天';
    } else {
      return '还剩${daysUntil}天';
    }
  }

  Widget _buildCountdownWidget(int daysUntil, bool isToday, bool isPast) {
    if (isToday) {
      return Text(
        '今天就是',
        style: TextStyle(
          fontSize: 18,
          fontWeight: FontWeight.bold,
          color: widget.isGrayedOut ? Colors.grey.shade400 : Colors.red.shade500,
        ),
      );
    } else if (isPast) {
      return RichText(
        text: TextSpan(
          children: [
            TextSpan(
              text: '${-daysUntil}',
              style: TextStyle(
                fontSize: 24,
                fontWeight: FontWeight.bold,
                color: widget.isGrayedOut ? Colors.grey.shade400 : Colors.red.shade500,
              ),
            ),
            TextSpan(
              text: '天前',
              style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.bold,
                color: widget.isGrayedOut ? Colors.grey.shade400 : Colors.grey.shade600,
              ),
            ),
          ],
        ),
      );
    } else {
      return RichText(
        text: TextSpan(
          children: [
            TextSpan(
              text: '$daysUntil',
              style: TextStyle(
                fontSize: 24,
                fontWeight: FontWeight.bold,
                color: widget.isGrayedOut ? Colors.grey.shade400 : Colors.red.shade500,
              ),
            ),
            TextSpan(
              text: '天',
              style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.bold,
                color: widget.isGrayedOut ? Colors.grey.shade400 : Colors.grey.shade600,
              ),
            ),
          ],
        ),
      );
    }
  }

  void _showEditMenu(BuildContext context) {
    // 触觉反馈 - 长按使用中等强度震动
    HapticFeedback.mediumImpact();
    
    showModalBottomSheet(
      context: context,
      backgroundColor: Colors.transparent,
      builder: (context) => Container(
        decoration: const BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(20),
            topRight: Radius.circular(20),
          ),
        ),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            // 拖拽指示器
            Container(
              margin: const EdgeInsets.only(top: 12),
              width: 40,
              height: 4,
              decoration: BoxDecoration(
                color: Colors.grey.shade300,
                borderRadius: BorderRadius.circular(2),
              ),
            ),
            
            // 标题
            Padding(
              padding: const EdgeInsets.all(20),
              child: Row(
                children: [
                  Text(
                    widget.importantDay.emoji,
                    style: const TextStyle(fontSize: 24),
                  ),
                  const SizedBox(width: 12),
                  Expanded(
                    child: Text(
                      widget.importantDay.title,
                      style: const TextStyle(
                        fontSize: 18,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                ],
              ),
            ),
            
            // 编辑选项
            _buildEditOption(
              context,
              icon: Icons.edit,
              title: '编辑',
              subtitle: '修改日期、标题或备注',
              color: Colors.blue,
              onTap: () {
                Navigator.pop(context);
                _editImportantDay(context);
              },
            ),
            
            _buildEditOption(
              context,
              icon: Icons.copy,
              title: '复制',
              subtitle: '创建一个相似的重要日子',
              color: Colors.orange,
              onTap: () {
                Navigator.pop(context);
                _copyImportantDay(context);
              },
            ),
            
            _buildEditOption(
              context,
              icon: Icons.delete,
              title: '删除',
              subtitle: '永久删除这个重要日子',
              color: Colors.red,
              onTap: () {
                Navigator.pop(context);
                _deleteImportantDay(context);
              },
            ),
            
            const SizedBox(height: 20),
          ],
        ),
      ),
    );
  }

  Widget _buildEditOption(
    BuildContext context, {
    required IconData icon,
    required String title,
    required String subtitle,
    required Color color,
    required VoidCallback onTap,
  }) {
    return ListTile(
      leading: Container(
        width: 40,
        height: 40,
        decoration: BoxDecoration(
          color: color.withOpacity(0.1),
          borderRadius: BorderRadius.circular(10),
        ),
        child: Icon(icon, color: color, size: 20),
      ),
      title: Text(
        title,
        style: const TextStyle(
          fontWeight: FontWeight.w600,
          fontSize: 16,
        ),
      ),
      subtitle: Text(
        subtitle,
        style: TextStyle(
          color: Colors.grey.shade600,
          fontSize: 14,
        ),
      ),
      onTap: onTap,
    );
  }

  void _editImportantDay(BuildContext context) {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => AddImportantDayScreen(
          editingDay: widget.importantDay,
        ),
      ),
    );
  }

  void _copyImportantDay(BuildContext context) {
    final copiedDay = ImportantDay(
      id: DateTime.now().millisecondsSinceEpoch.toString(),
      title: '${widget.importantDay.title} (副本)',
      description: widget.importantDay.description,
      date: widget.importantDay.date.add(const Duration(days: 365)), // 复制到明年
      category: widget.importantDay.category,
      emoji: widget.importantDay.emoji,
      note: widget.importantDay.note,
    );
    
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => AddImportantDayScreen(
          editingDay: copiedDay,
        ),
      ),
    );
  }

  void _deleteImportantDay(BuildContext context) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('确认删除'),
        content: Text('确定要删除"${widget.importantDay.title}"吗？此操作无法撤销。'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () {
              Navigator.pop(context);
              Provider.of<ImportantDaysProvider>(context, listen: false)
                  .deleteImportantDay(widget.importantDay.id);
              ScaffoldMessenger.of(context).showSnackBar(
                SnackBar(
                  content: Text('已删除 ${widget.importantDay.title}'),
                  backgroundColor: Colors.red,
                ),
              );
            },
            style: TextButton.styleFrom(foregroundColor: Colors.red),
            child: const Text('删除'),
          ),
        ],
      ),
    );
  }
}